/**
 * @description 与原生交互
 */

import {
  trainScanSignInApi,
  trainingRegisterApi,
  getMyResearchStatusApi,
  isInTrainClassApi,
} from '@/api/scan'
import { Toast } from 'vant'
import $router from '@/router'

var u = navigator.userAgent
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 //android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端

const Bridge = (function () {
  function setupWebViewJavascriptBridge(callback) {
    if (isAndroid) {
      if (window.WebViewJavascriptBridge) {
        callback(window.WebViewJavascriptBridge)
      } else {
        document.addEventListener(
          'WebViewJavascriptBridgeReady',
          function () {
            callback(window.WebViewJavascriptBridge)
          },
          false
        )
      }
      return
    }
    if (isiOS) {
      if (window.WebViewJavascriptBridge) {
        return callback(window.WebViewJavascriptBridge)
      }
      if (window.WVJBCallbacks) {
        return window.WVJBCallbacks.push(callback)
      }
      window.WVJBCallbacks = [callback]
      var WVJBIframe = document.createElement('iframe')
      WVJBIframe.style.display = 'none'
      WVJBIframe.src = 'https://__bridge_loaded__'
      document.documentElement.appendChild(WVJBIframe)
      setTimeout(function () {
        document.documentElement.removeChild(WVJBIframe)
      }, 0)
    }
  }

  function Bridge() {
    this.isInit = false
  }

  Bridge.prototype.init = function () {
    if (isAndroid) {
      setupWebViewJavascriptBridge(function (bridge) {
        bridge.init(function (message, responseCallback) {
          console.log('Bridge init', message)
          responseCallback(JSON.stringify(message))
        })
      })
    }
    this.isInit = true
  }

  Bridge.prototype.callhandler = function (name, data, callback) {
    setupWebViewJavascriptBridge(function (bridge) {
      bridge.callHandler(name, data, callback)
    })
  }

  Bridge.prototype.registerhandler = function (name, callback) {
    if (!this.isInit) {
      this.init()
    }
    setupWebViewJavascriptBridge(function (bridge) {
      bridge.registerHandler(name, function (data, responseCallback) {
        callback(data, responseCallback)
      })
    })
  }

  Bridge.prototype.register = function () {
    this.registerhandler('businessScanRes', (data, responseCallback) => {
      //接收原生回传过来的值
      let scanRes = data
      if (scanRes.indexOf('signIn') > -1) {
        let obj = {}
        let scanResArr = scanRes.split(',')
        if (scanRes.indexOf('traningSignId') > -1) {
          obj = { trainClassId: scanResArr[1], trainSignInId: scanResArr[3] }
        } else {
          obj = { trainClassId: scanResArr[1] }
        }
        trainScanSignInApi(obj).then((res) => {
          Toast(res.msg)
        })
        return
      } else if (scanRes.indexOf('register') > -1) {
        let scanResArr = scanRes.split(',')
        trainingRegisterApi({ classId: scanResArr[1] }).then((res) => {
          Toast(res.msg)
        })
        return
      } else if (scanRes.indexOf('investigate') > -1) {
        let scanResArr = scanRes.split(',')
        isInTrainClassApi({
          classId: scanResArr[1],
          researchId: scanResArr[2],
        }).then((res) => {
          let type
          if (res.isInTrainClass == 4) {
            // 1: 调查未开始 2: 未做调查, 可进入调查  3: 已做调查 4: 调查结束
            type = 1
          } else {
            type = 0
          }
          $router.push({
            name: 'questionnaireTitlePage',
            params: {
              type, //是否参与过当前调查
              researchId: scanResArr[2], //当前调查问卷id
              taskId: -1, //是否从培训中过来
            },
          })
        })
      } else if (scanRes.indexOf('inquiryWeChatShare') > -1) {
        let id = scanRes.split('inquiryId=')[1].split('&')[0]
        getMyResearchStatusApi({ id: id }).then((res) => {
          let type
          if (res.data == 4) {
            // 1: 调查未开始 2: 未做调查, 可进入调查  3: 已做调查 4: 调查结束
            type = 1
          } else {
            type = 0
          }
          $router.push({
            name: 'questionnaireTitlePage',
            params: {
              type, //是否参与过当前调查
              researchId: id, //当前调查问卷id
              taskId: -1, //是否从培训中过来
            },
          })
        })
        return
      } else {
        window.location.href = scanRes
      }
      responseCallback('200') //把值返回给原生
    })
  }
  return Bridge
})()

export default new Bridge()
